﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using XConductor.Domain.Seedwork.Playback;
using XConductor.Domain.Seedwork.Playback.Settings;
using XConductor.Domain.WP8.Playback.Settings;

namespace XConductor.Domain.WP8.Playback
{
    public class AudioPlayer : IAudioPlayer
    {
        private bool m_inited = false;
        private bool m_playing = false;
        private bool m_paused = false;
        
        private AudioPlayerSettings m_settings;

        public async Task Play()
        {
            if (this.m_inited)
            {
                this.m_playing = true;

                this.m_settings.MediaElement.Play();
            }
        }

        public async Task Stop()
        {
            if (this.m_inited)
            {
                this.m_playing = false;
                this.m_inited = false;

                this.m_settings.MediaElement.Stop();
            }
        }

        public async Task Pause()
        {
            if (this.m_inited)
            {
                this.m_paused = this.m_playing;

                this.m_settings.MediaElement.Pause();
            }
        }

        public async Task Initialize(IAudioPlayerSettings settings)
        {
            this.m_settings = settings as AudioPlayerSettings;

            if (this.m_settings != null && this.m_settings.IsValid() && !this.m_inited)
            {
                this.m_inited = true;

                var stream = await this.m_settings.InputFile.OpenAsync(Windows.Storage.FileAccessMode.Read);

                this.m_settings.MediaElement.SetSource(stream, this.m_settings.InputFile.FileType);
            }
        }

        public bool Initialized
        {
            get { return this.m_inited; }
        }

        public bool Playing
        {
            get { return this.m_playing; }
        }

        public bool Paused
        {
            get { return this.m_paused; }
        }
    }
}
